/**
 * 
 */
package com.effectiv.gooruda.mvc.argumentresolver;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * @author Dhrubo
 * 
 */
@Slf4j
public class AjaxResponseWebArgumentResolver implements WebArgumentResolver, ApplicationContextAware {
	
	private ApplicationContext context;
	
	@Override
	public Object resolveArgument(MethodParameter param,
			NativeWebRequest request) throws Exception {
		Object argument = UNRESOLVED;

		log.info("Resolving custom argument");
		
		if (param.getParameterType().equals(AjaxResponse.class)) {
			AjaxResponse response = BeanUtils.instantiate(AjaxResponse.class);
			
			log.info("Param = {}", param.getMethod().getName());
			log.info("Param = {}", param.getMethod().getDeclaringClass().getSimpleName().toLowerCase());
			
			String key = param.getMethod().getDeclaringClass().getSimpleName().toLowerCase() + "." + param.getMethod().getName().toLowerCase();
			
			log.info("Success key = {}", key);
			
			
			String msg = context.getMessage(key + ".SUCCESS", null, request.getLocale());
			
			response.setMessage(msg);
				
			argument = response;
		}

		log.info("Resolving custom argument = {}", argument);
		
		return argument;
	}

	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.context = context;
	}

}
